package com.itshen.thread;

public class SynchronizedDemo {

    public static void main(String[] args) {
        Factory factory = new Factory();
        // A和B消费
        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                try {
                    factory.decrement();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                try {
                    factory.decrement();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();

        // C和D生产
        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                try {
                    factory.increment();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "C").start();
        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                try {
                    factory.increment();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "D").start();
    }
}

class Factory {

    private int number = 0;

    public synchronized void increment() throws Exception {
        //1 判断，用while防止虚假唤醒
        while (number != 0) {
            // 等待
            this.wait();
        }
        //2 干活
        number++;
        System.out.println(Thread.currentThread().getName() + "\t" + number);
        //3 通知
        this.notifyAll();
    }

    public synchronized void decrement() throws Exception {
        //1 判断
        while (number == 0) {
            this.wait();
        }
        //2 干活
        number--;
        System.out.println(Thread.currentThread().getName() + "\t" + number);
        //3 通知
        this.notifyAll();
    }
}
